package org.kitten.core.io;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

public class MyFilenameFilter implements FilenameFilter {

	/*
	 * filename match strategy(endsWith,startsWith or equals)
	 */
	public final static int STARTS_WITH = 1;
	public final static int ENDS_WITH = 2;
	public final static int EQUALS = 3;
	public final static int INDEX_OF = 4;

	private int matchMode = ENDS_WITH;
	private boolean ignoreCase = false;
	
	/**
	 * 在用File.listFiles(MyFilenameFilter)时需要设置为true;
	 */
	private boolean excludeFolders = false;

	private Collection<String> includeList = new HashSet<String>();
	private Collection<String> excludeList = new HashSet<String>();

	public MyFilenameFilter() {
		this(ENDS_WITH);
	}

	public MyFilenameFilter(int matchMode) {
		this.matchMode = matchMode;
	}

	public MyFilenameFilter(int matchMode, boolean ignoreCase) {
		this.matchMode = matchMode;
		this.ignoreCase = ignoreCase;
	}

	public void addExtension(String extension) {
		includeList.add(extension);
	}

	public void addExclude(String exclude) {
		excludeList.add(exclude);
	}

	public void addExtensions(String[] extensions) {
		if (extensions!=null) {
			for (int i = 0; i < extensions.length; i++) {
				addExtension(extensions[i]);
			}
		}
	}

	public void addExcludes(String[] exs) {
		if (exs!=null) {
			for (int i = 0; i < exs.length; i++) {
				addExclude(exs[i]);
			}
		}
	}

	public boolean accept(File dir, String name) {
		File f = new File(dir + File.separator + name);
		if (f.isDirectory()) {
			if (excludeFolders) {
				return false;
			}else{
				return true;
			}
		} else {
			return decide(f);
		}
	}

	public void setExcludeFolders(boolean excludeFolders) {
		this.excludeFolders = excludeFolders;
	}

	private boolean decide(File f) {
		if (includeList.size() == 0) {
			for (Iterator it = excludeList.iterator(); it.hasNext();) {
				String name = f.getName();
				String givenExclude = (String) it.next();
				if (name.endsWith(givenExclude)) {
					return false;
				}
			}
			return true;
		} else {
			for (Iterator it = includeList.iterator(); it.hasNext();) {
				String name = f.getName();
				String givenExt = (String) it.next();
				if (ignoreCase) {
					name = name.toUpperCase();
					givenExt = givenExt.toUpperCase();
				}
				switch (matchMode) {
				case ENDS_WITH:
					if (name.endsWith(givenExt)) {
						return true;
					}
					break;
				case STARTS_WITH:
					if (name.startsWith(givenExt)) {
						return true;
					}
					break;
				case EQUALS:
					if (name.equals(givenExt)) {
						return true;
					}
					break;
				case INDEX_OF:
					if (name.indexOf(givenExt)!=-1) {
						return true;
					}
					break;
				}
			}
			return false;
		}
	}
}
